package com.example.springbotorderrabbitmqproducer.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MsgSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String msg, int delayTime) {
        System.out.println("msg=" + ",delayTime" + delayTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //发送消息至 延时队列的exchange中
        this.rabbitTemplate.convertAndSend("exchange.demo.delay", "routingkey.demo.delay", msg, message -> {
            //设置消息的过期时间，过期之后会转入死信队列
            message.getMessageProperties().setExpiration(delayTime + "");
            message.getMessageProperties().setContentEncoding("UTF-8");
            System.out.println(sdf.format(new Date()) + " Delay sent.");
            return message;
        });
    }
}
